package com.handsome.controller;

import com.handsome.entity.HsMember;
import com.handsome.service.MemberService;
import com.handsome.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {

    @Autowired
    private MemberService memberService;

    @ModelAttribute
    public HsMember getHsMemberEntity(HsMember memberEntity) {
        System.out.println("getHsMemberEntity 执行");
        System.out.println("memberEntity = [" + memberEntity.getUsername() + "]");
        return memberEntity;
    }


    @RequestMapping("/admin/login")
    public String index() {
        return "login";
    }

    @RequestMapping("/admin/login/loginByPassword")
    @ResponseBody
    Result loginByPassword(HsMember member) {
        Result result = memberService.loginByPassword(member);
        if (result.getData() != null) {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(member.getUsername(), member.getPassword());
            try {
                subject.login(token);
            } catch (UnknownAccountException | IncorrectCredentialsException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


}
